<?php

namespace Admin\Controller;

class LinkController extends CommonController
{
    // 列表
    public function lists()
    {
        $map = array();

        $key = I('request.key', '', 'trim');

        if ($key) {
            $key_type = I('request.key_type', 0, 'intval');
            if ($key_type == '1') {
                $map['link_name'] = array('like', '%' . $key . '%');
            }
            if ($key_type == '2') {
                $map['link_url'] = array('like', '%' . $key . '%');
            }
            if ($key_type == '3') {
                $map['notes'] = array('like', '%' . $key . '%');
            }
        }

        $count = M("Link")->where($map)->count();
        $Page  = pager($count);
        $list  = M("Link")->where($map)->order('sort desc, id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();

        $this->assign('list', $list);
        $this->assign('page', $Page->fshow());

        $this->display();
    }

    // 新增
    public function add()
    {
        if (IS_POST) {
            $data = D("Link");
            if (!$data->create()) {
                $this->error($data->getError());
            } else {
                $data->username = session('ytata.username');
                $data->add();
                $this->success('保存完成');
            }
        } else {
            $this->display();
        }
    }

    // 编辑
    public function edit()
    {
        if (IS_POST) {
            $data = D("Link");
            if (!$data->create()) {
                $this->error($data->getError());
            } else {
                $data->save();
                $this->success('保存完成');
            }
        } else {
            $id = I('get.id', '', 'intval');
            if ($id) {
                $data      = M("Link");
                $map['id'] = $id;
                $show      = $data->where($map)->limit(1)->find();
                $this->assign('show', $show);
                $this->display();
            } else {
                $this->error('非法请求');
            }
        }
    }

    // 删除
    public function delete()
    {
        $ids = I('request.id');
        $ids = is_array($ids) ? implode(",", $ids) : $ids;
        if ($ids && preg_match("/^(\d{1,10},)*(\d{1,10})$/", $ids)) {
            $s = M("Link")->delete($ids);
            $this->success("成功删除{$s}条数据");
        } else {
            $this->error('请选择要删除的信息！');
        }
    }
}